package cn.okcode.api.framework.result;

import cn.hutool.core.util.ClassUtil;
import cn.okcode.api.framework.Callee;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 原始结果处理器，这里的原始结果即指的返回字符串
 *
 * @author pyk13
 */
public class RawResultHandler implements ResultHandler {
    @Override
    public String ok(Object res) {
        if (res == null) {
            return "";
        }
        if (res instanceof String) {
            return res.toString();
        }

        if (ClassUtil.isBasicType(res.getClass())) {
            return res.toString();
        }

        //return JSON.toJSONString(res, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        //注意：这里不能加上SerializerFeature.DisableCircularReferenceDetect参数，否则对象出现循环引用的时候fastjson不会自动停止遍历
        return JSON.toJSONString(res, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String err(Callee callee, String msg, Throwable e) {
        String message = e.getLocalizedMessage();
        throw new RawResultException(msg + ":" + message, e);
    }
}
